/*
 * Copyright 2007 Gergely Kis
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.gwthtml.util;

import java.io.Reader;
import java.util.List;

import org.cyberneko.html.parsers.DOMFragmentParser;
import org.jdom.Document;
import org.jdom.input.DOMBuilder;
import org.jdom.input.SAXBuilder;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.html.HTMLDocument;
import org.xml.sax.InputSource;

import com.sun.org.apache.html.internal.dom.HTMLDocumentImpl;

public class HTMLParser {
	
	private static SAXBuilder saxBuilder;
	private static DOMBuilder domBuilder;
	
	static {
		saxBuilder = new SAXBuilder("com.gwthtml.util.HTMLSAXParser");
		saxBuilder.setFactory(GWTJDOMFactory.getInstance());
		domBuilder = new DOMBuilder();
		domBuilder.setFactory(GWTJDOMFactory.getInstance());
	}
	
	public static Document parseHtmlDocument(Reader reader) {
		try {
			return saxBuilder.build(reader);
		} catch (Exception e) {
			return null;
		}
	}
	
	public static List parseHtmlFragment(Reader reader) {
        DOMFragmentParser parser = new DOMFragmentParser();
        try {
			parser.setProperty("http://cyberneko.org/html/properties/names/elems", "lower");
		} catch (Exception e) {
		}
        HTMLDocument document = new HTMLDocumentImpl();
        DocumentFragment fragment = document.createDocumentFragment();
        try {
			parser.parse(new InputSource(reader), fragment);
		} catch (Exception e) {
			return null;
		}
        return domBuilder.build(fragment);
	}

}
